package cn.sofwin.os.service.Impl;

import cn.sofwin.core.mvc.service.impl.BaseServiceImpl;
import cn.sofwin.core.mvc.support.annotation.BaseDao;
import cn.sofwin.core.mvc.support.api.RequestResult;
import cn.sofwin.core.mvc.support.api.StatusCode;
import cn.sofwin.core.mvc.support.utils.Encodes;
import cn.sofwin.core.rbac.service.AuthService;
import cn.sofwin.os.dao.UserDao;
import cn.sofwin.os.entity.User;
import cn.sofwin.core.mvc.support.bean.info.Module;
import cn.sofwin.os.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 用户服务层
 * @author LetCode
 * @version 1.0
 * @date 2020-04-23 11:28:34
 *
 */
@CacheConfig(cacheNames = "os_user")
@Service("userService")
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {
	
	@BaseDao
	UserDao userDao;

	@Autowired
	RedisTemplate redisTemplate;

	@Autowired
	AuthService authService;


	@Cacheable
	@Override
	public Module loadModuleInfo(){
		Module module = new Module("用户", "user");

		// 增加表头字段信息
		module.addColumn("id", "序号")
		      .addColumn("username", "用户名")
		      .addColumn("salt", "加盐")
		      .addColumn("password", "密码")
		      .addColumn("nickname", "昵称")
		      .addColumn("status", "状态：-1.删除，0.停用，1.正常");

		// 增加搜索字段信息
		module.addSearchField("title", "名称");

		// 增加视图地址
		module.addView("list", "/home/list/user")
		      .addView("form", "/home/form/user");

		// 增加数据请求接口
		module.addApi("base", "/os/user");

		return module;
	}

	/**
	 * 重写create方法，添加自定义的业务逻辑
	 * @param user
	 * @return
	 */
	@Override
	public User create(User user) {
		// 产生随机的字符串，用于混淆密码
		String salt = Encodes.salt();
		// 加密明文密码
		String password = user.getPassword();
		password = Encodes.password(password, salt);
		// 设置加密结果
		user.setSalt(salt);
		user.setPassword(password);
		userDao.insert(user);
		return user;
	}

    @Override
    public RequestResult login(User loginUser) {
		RequestResult result;
		User user = userDao.selectByUsername(loginUser.getUsername());
		if(user == null){
			result = new RequestResult(StatusCode.UsernameError);
		}else{
			String password = Encodes.password(loginUser.getPassword(), user.getSalt());
			if(password.equals(user.getPassword())){
				result = new RequestResult();
				// 清除敏感信息
				user.setSalt(null);
				user.setPassword(null);
				String token = authService.setUserCache(user);

				// 将Token和用户信息返回给前端
				result.appendData("token", token);
				result.appendData("user", user);
			}else{
				result = new RequestResult(StatusCode.PasswordError);
			}
		}

        return result;
    }
}